{extend name="common/base"/}
{block name="style"}
<style>
	/* 保持原有样式不变 */
	body { display: flex; overflow: hidden; height: 100vh; }
	::-webkit-scrollbar { display: none; width: 6px; height: 6px; }
	::-webkit-scrollbar-thumb { border-radius: 10px; background-color: #e1e1e1; }
	.layui-tab{margin:0;}
	.container { display: flex; flex: 1; flex-direction: column; overflow: hidden; padding:12px;}
	.file-container { display: flex; flex: 1; flex-direction: column; overflow: hidden; border-radius: 2px; background: #ffffff; box-shadow: rgba(0, 0, 0, 0.05) 0 1px 2px 0; }
	.file-item {display: flex; flex: 1; justify-content: space-between; overflow: hidden; }
	.file-header {padding-top: 4px; }

	/** 分组 **/
	.file-item .group { position: relative; display: flex; flex-direction: column; padding-top: 8px; width: 200px; border-right: 1px solid #f6f6f6; }
	.file-item .group ul::-webkit-scrollbar { display: block; }
	.file-item .group ul { flex: 1; overflow: hidden; overflow-y: auto; }
	.file-item .group ul li {display: flex; align-items: center; justify-content: space-between; cursor:pointer; padding: 0 12px; height: 38px; font-size: 13px; color: #666666; }
	.file-item .group ul li i.iconfont{ margin-right:8px; font-size:24px; color:#E1AF1A; font-weight:800;}
	.file-item .group ul li > span { display: flex; flex: 1; overflow: hidden; margin-right: 0.5rem; text-overflow: ellipsis; white-space: nowrap; }
	.file-item .group ul li.active { background: #edefff; }
	.file-item .group ul li:hover { background: #f5f7fa; }
	.file-item .group ul li .dropdown:hover dl { display: block; }
	.file-item .group ul li .dropdown dl { position: absolute; top: 36px; right: -15px; z-index: 10000; display: none; padding: 5px 0; width: 88px; border-radius: 2px; text-align: center; background-color: #ffffff; box-shadow: #cccccc 0 0 10px; }
	.file-item .group ul li .dropdown dl dd { height: 32px; line-height: 32px; }
	.file-item .group ul li .dropdown dl dd:hover { color: #4a5dff; background-color: #edefff; }
	.file-item .group ul li .dropdown dl::before { position: absolute; top: -16px; left: 44px; z-index: 12; display: block; padding: 0; width: 0; height: 0; border-top: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 8px solid #ffffff; border-left: 8px solid transparent; content: ""; box-sizing: content-box; }
	.file-item .group .footer { display: flex; align-items: center; justify-content: center; width: 100%; height: 50px; border-top: 1px solid #f2f2f2; border-right: 1px solid #f2f2f2; }

	/** 菜单 **/
	.file-item .attach #move:hover { position: relative; opacity: 1; }
	.file-item .attach #move:hover .dropdown { display: block; background-color: #ffffff; }
	.file-item .attach .dropdown { position: absolute; top: 38px; z-index: 100000; display: none; padding: 5px 0; width: 150px; border: 1px solid #dddddd; text-align: left; background-color: #ffffff; line-height: 1.6; }
	.file-item .attach .dropdown em { font-size: 13px; font-weight: 400; color: #333333; font-style: normal; }
	.file-item .attach .dropdown em { display: block; clear: both; padding: 6px 20px; white-space: nowrap; }
	.file-item .attach .dropdown em:hover { background: #eeeeee; }
	.file-item .attach .dropdown em:first-child { font-size: 12px; color: #999999; }
	.file-item .attach .dropdown::before { position: absolute; top: -16px; left: 21px; z-index: 12; display: block; padding: 0; width: 0; height: 0; border-top: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 8px solid #ffffff; border-left: 8px solid transparent; content: ""; box-sizing: content-box; }
	.file-item .attach .dropdown::after { position: absolute; top: -18px; left: 20px; z-index: 10; display: block; padding: 0; width: 0; height: 0; border-top: 9px solid transparent; border-right: 9px solid transparent; border-bottom: 9px solid #cccccc; border-left: 9px solid transparent; content: ""; box-sizing: content-box; }

	/** 文件 **/
	.file-item .attach { position: relative; display: flex; flex: 1; flex-direction: column; }
	.file-item .attach .header { display: flex; align-items: center; justify-content: space-between; padding:12px 15px; margin:0;}
	.file-item .attach .header .search{ display: flex; }
	.file-item .attach .header .search input { height: 30px; border-color: #eeeeee; border-top-right-radius: 0; border-bottom-right-radius: 0; }
	.file-item .attach .header .search button { border-color: #eeeeee; background: #f5f7fa; border-top-left-radius: 0; border-bottom-left-radius: 0; }
	.file-item .attach .header .search button:hover { background-color: #eeeeef; }
	.file-item .attach .subject { flex: 1; overflow: hidden; overflow-y: auto; margin: 10px; box-sizing: border-box; }
	.file-item .attach .subject:hover::-webkit-scrollbar { display: block; }
	.file-item .attach .subject ul { display: flex; flex-wrap: wrap; }
	.file-item .attach .subject ul li { position: relative; width: 200px; height: 240px; margin: 5px; padding: 9px; border: 1px solid rgba(0, 0, 0, 0.05); border-radius: 3px; transition: all 0.2s ease-in-out; }
	.file-item .attach .subject ul li:hover {border: 1px solid #cccccc; }
	.file-item .attach .subject ul li.on {border: 1px solid #ff5722; }
	.file-item .attach .subject ul li img { width: 200px; height: 200px; border-radius: 2px; cursor: pointer; }
	.file-item .attach .subject ul li video { width: 200px; height: 200px; border-radius: 3px; }
	.file-item .attach .subject ul li p {  margin: 5px 0 0; width: 98%; font-size: 13px; text-align: center;word-wrap: break-word;white-space: pre-line;overflow-wrap: break-word;  }
	.file-item .attach .subject ul li::after {position: absolute; width:22px; height:22px; right: -1px; bottom: -1px; display: none; font-size: 14px; font-family: layui-icon, serif; border-radius:3px 0 3px 0; text-align: center; color: #ffffff; background: #ff5722; content: "\e605"; line-height: 24px; }
	.file-item .attach .subject ul li.on::after { display: block; }
	.file-item .attach .subject ul li .layui-btn-group{position:absolute; top:3px; right:3px; display:none;}
	.file-item .attach .subject ul li:hover .layui-btn-group{display:block}

	.file-item .attach .footer { display: flex; align-items: center; justify-content: end; padding: 5px 15px 0; height: 45px; border-top: 1px solid #f2f2f2; text-align: center; background: #ffffff; }

	/** 无数据 **/
	.file-item .empty { display: flex; flex: 1; align-items: center; flex-direction: column; justify-content: center; overflow: hidden; text-align: center; color: #cccccc; }
	.file-item .empty i { font-size: 180px; }
	.file-item .empty p { width: 180px; text-align: center; }

	/** 懒加载样式 **/
	.lazyload-placeholder {
		background: #f5f5f5;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ddd;
	}
	.lazyload-loading {
		background: #f5f5f5 url('/static/images/loading.gif') no-repeat center;
		background-size: 30px 30px;
	}

	/* 图片预览放大样式 */
	.image-preview-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.9);
		z-index: 99999;
		display: none;
		justify-content: center;
		align-items: center;
		padding: 20px;
	}
	.image-preview-container {
		position: relative;
		max-width: 90%;
		max-height: 90%;
	}
	.preview-image {
		max-width: 100%;
		max-height: 85vh;
		object-fit: contain;
	}
	.close-preview {
		position: absolute;
		top: -40px;
		right: -40px;
		color: white;
		font-size: 30px;
		cursor: pointer;
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	/* 上一张/下一张按钮 */
	.prev-image, .next-image {
		position: fixed;
		top: 50%;
		transform: translateY(-50%);
		color: white;
		font-size: 40px;
		cursor: pointer;
		width: 60px;
		height: 60px;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(0, 0, 0, 0.3);
		border-radius: 50%;
		transition: background 0.3s;
	}
	.prev-image:hover, .next-image:hover {
		background: rgba(0, 0, 0, 0.5);
	}
	.prev-image {
		left: 30px;
	}
	.next-image {
		right: 30px;
	}
	/* 图片计数 */
	.image-counter {
		position: absolute;
		bottom: -30px;
		left: 50%;
		transform: translateX(-50%);
		color: white;
		font-size: 14px;
		background: rgba(0, 0, 0, 0.5);
		padding: 5px 10px;
		border-radius: 12px;
	}
	.image-preview-modal.show {
		display: flex;
	}
</style>
{/block}
<!-- 主体 -->
{block name="body"}
<div class="container">
	<div class="file-container">
		<div class="file-item">
			<!-- 文件 -->
			<div class="attach">
				<!-- 工具 -->
				<form class="layui-form" lay-filter="barsearchform" style="display:block; margin:0;padding:0;">
					<div class="header">
						<div class="layui-btn-group">
							<!--<span class="layui-btn layui-btn-sm layui-btn-normal" id="fileUpload">上传文件</span>-->
							<span class="layui-btn layui-btn-sm layui-btn-danger" id="fileDelete">批量删除</span>
							<!--<span class="layui-btn layui-btn-sm layui-btn-warm" id="fileMove">移动至 <i class="layui-icon layui-icon-triangle-d"></i></span>-->
							<span style="margin-left:36px;"><input type="checkbox" name="select_all" lay-filter="all" title="全选"></span>
						</div>

						<div class="search">
							<input type="hidden" name="limit" value="{$limit}" />
							<input type="hidden" name="page" value="{$page}" />
							<label><input type="hidden" id="keywords" name="keywords" placeholder="请输入名称" autocomplete="off" class="layui-input"></label>
							<!--<button type="button" class="layui-btn layui-btn-sm layui-btn-primary" lay-submit="" lay-filter="webform"><i class="layui-icon layui-icon-search"></i></button>-->
						</div>
					</div>
				</form>
				<!-- 主体 -->
				<div class="subject">
					<ul class="layui-fluid" id="filesBox"></ul>
				</div>
				<!-- 页脚 -->
				<div class="footer">
					<div id="laypage"></div>
				</div>
			</div>
		</div>
	</div>
</div>
<!-- 图片预览放大层 -->
<div class="image-preview-modal" id="imagePreviewModal">
	<div class="image-preview-container">
		<img src="" alt="预览图片" class="preview-image" id="previewImage">
		<div class="close-preview" id="closePreview">×</div>
		<div class="prev-image" id="prevImage">←</div>
		<div class="next-image" id="nextImage">→</div>
		<div class="image-counter" id="imageCounter">1/1</div>
	</div>
</div>
<script type="text/html" id="toolbarDemo">
	<h3 class="h3-title" style="height:28px;">审批列表</h3>
</script>
{/block}
<!-- /主体 -->

<!-- 脚本 -->
{block name="script"}
<!-- 引入懒加载插件 -->
<script src="{__GOUGU__}/layui/lazyload.min.js"></script>
<script>
	const moduleInit = ['tool'];
	function gouguInit() {
		var table = layui.table, tool = layui.tool ,form = layui.form,laypage = layui.laypage,upload = layui.upload, element=layui.element, dropdown=layui.dropdown ;
		element.on('tab(tab)', function(data){
			$('[name="tab"]').val(data.index);
			$('[lay-filter="webform"]').click();
			return false;
		});

		//监听多选框点击事件  通过 lay-filter="menu"来监听
		form.on('checkbox(all)', function (data) {
			let val = data.value;
			if(data.elem.checked){
				//判断当前多选框是选中还是取消选中
				$('#filesBox li').addClass('on');
			}
			else{
				$('#filesBox li').removeClass('on');
			}
		});

		var uploadInst = upload.render({
			elem: '#fileUpload'
			,url: "/admin/api/upload"
			, accept: 'file' //普通文件
			, exts: 'jpeg|jpg|png|gif|doc|docx|ppt|pptx|xls|xlsx|pdf|zip|rar|7z|txt|mp4|psd|svg' //只允许上传文件
			, before: function (obj) {
				layer.msg('上传中...', { time: 3600000 });
			}
			,done: function (res) {
				layer.msg(res.msg);
				$('[lay-filter="webform"]').click();
			}, error: function (index, upload) {
				layer.msg('上传失败');
			}
		});

		$('body').on('click','.add-new',function(){
			add_group(0,'');
		});

		$('#group').on('click','li',function(){
			let id=$(this).data('id');
			$(this).siblings().removeClass('active');
			$(this).addClass('active');
			$('[name="group_id"]').val(id);
			$('[lay-filter="webform"]').click();
		});

		$('#fileDelete').on('click',function(){
			let select_array = [];
			const keywords = $('#keywords').val();
			$('#filesBox').find('li.on').each(function(index,item){
				select_array.push($(item).data('title'));
			})
			if(select_array.length<1){
				layer.msg('请先选择文件');
			}
			else{
				layer.confirm('确定要删除这些文件吗？请慎重', { icon: 3, title: '提示' }, function (index) {
					let callback = function (e) {
						layer.closeAll();
						layer.msg(e.msg);
						// 删除成功后刷新页面
						if(e.code==0){
							location.reload();
						}
					}
					tool.delete("/admin/files/delete", {ids:select_array.join(','),path:keywords}, callback);
				});
			}
		});

		function add_group(id,val){
			var title = '新增分组';
			if(id>0){
				title = '编辑分组';
			}
			layer.prompt({
				title: title,
				value: val,
				yes: function(index, layero) {
					var value = layero.find(".layui-layer-input").val();
					if (value!='') {
						let callback = function (e) {
							layer.msg(e.msg);
							if(e.code==0){
								location.reload();
							}
						}
						tool.post("/admin/files/add_group", {id: id,title: value}, callback);
						layer.close(index);
					} else {
						layer.msg('请填写分组名称');
					}
				}
			})
		}
		const urlParams = new URLSearchParams(window.location.search);
		const keywordsValue = urlParams.get('keywords');
		const keywordsElement = document.getElementById('keywords');
		if (keywordsElement) {
			keywordsElement.value = keywordsValue;
		}
		var data = form.val('barsearchform');
		get_files(data);
		get_group();

		function get_group(param){
			$.ajax({
				url:"/admin/files/get_group",
				success:function(res){
					if(res.code==0){
						var group=res.data,item='';
						if(group.length>0){
							for(var a=0;a<group.length;a++){
								item+='<li data-id="'+group[a].id+'" data-title="'+group[a].title+'"><i class="iconfont icon-sucaiziyuan"></i>'+group[a].title+'<i class="layui-icon layui-icon-more-vertical dropdown-on"></i></li>';
							}
							$('#group').append (item);
							dropdown.render ({
								elem: '.dropdown-on',
								trigger: 'hover',
								align: 'right',
								data: [{
									title: '重命名分组',
									id: 100
								},{
									title: '删除该分组',
									id: 101
								}],
								click: function(data, othis){
									let id = $(this.elem).parent().data('id');
									let title = $(this.elem).parent().data('title');
									if(data.id==100){
										add_group(id,title);
									}else{
										del_group(id);
									}
								}
							});
						}
						group.push({id:0,title:'未分组'});
						dropdown.render({
							elem: '#fileMove',
							data: group,
							click: function(obj){
								let select_array = [];
								$('#filesBox').find('li.on').each(function(index,item){
									select_array.push($(item).data('id'));
								})
								if(select_array.length<1){
									layer.msg('请先选择文件');
								}
								else{
									layer.confirm('确定要把选中的文件移动到『'+obj.title+'』分组吗？', { icon: 3, title: '提示' }, function (index) {
										let callback = function (e) {
											layer.closeAll();
											layer.msg(e.msg);
											$('[lay-filter="webform"]').click();
										}
										tool.delete("/admin/files/move", {group_id:obj.id,ids:select_array.join(',')}, callback);
									});
								}
							}
						});
					}
				}
			});
		}

		function del_group(id) {
			layer.confirm('确定要删除该分组吗？请慎重', { icon: 3, title: '提示' }, function (index) {
				let callback = function (e) {
					layer.closeAll();
					layer.msg(e.msg);
					if(e.code==0){
						location.reload();
					}
				}
				tool.delete("/admin/files/del_group", {ids:id}, callback);
			});
		}


		function get_files(param){
			var loadIndex = layer.load(0);
			$.ajax({
				url:"/admin/files/index",
				data:param,
				complete:function(){
					setTimeout(function(){
						layer.close(loadIndex)
					}, 200);
				},
				success:function(res){
					$('[name="select_all"]').prop('checked', false);
					form.render('checkbox');
					let jsonString = JSON.parse(res);
					laypage.render ({
						elem: 'laypage',
						limit:param ['limit'],
						curr:param ['page'],
						count: jsonString.count,
						jump: function (obj, first){
							if (!first){
								var data = form.val ('barsearchform');
								data ['page'] = obj.curr;
								get_files (data);
							}
						}
					});
					var item=jsonString.data,li='';
					if(item.length>0){
						for(var a=0;a<item.length;a++){
							let image = ['jpg','jpeg','png','gif'];
							let doc = ['doc','docx','xls','xlsx','ppt','pptx','txt','pdf','zip','rar','directory'];
							let path='/static/home/images/icon/file.png';
							if (image.includes (item [a].image_extension)) {
								path=item [a].relative_path;
								li+='<li class="layui-col-space2"  data-id="'+item[a].id+'" data-title="'+item[a].image_name+'" data-ext="'+item[a].image_name+'" data-image="true" data-image-src="'+path+'"><img class="lazyload" data-src="'+path+'" src="" alt="'+item[a].filename+'" class="file-item"><p title="'+item[a].image_name+'">'+item[a].image_name+'</p><div style="position: absolute; top: 5px; right: 5px;"><span data-href="'+path+'" class="layui-btn layui-btn-xs layui-btn-normal file-view-images">预览</span><span class="layui-btn layui-btn-xs layui-btn-danger file-del">删除</span></div></li>';
							} else if (doc.includes (item [a].image_extension)){
								path='/static/home/images/icon/'+item [a].image_extension+'.png';
								li+='<li class="layui-col-space2"  data-id="'+item[a].id+'" data-title="'+item[a].image_name+'" data-ext="'+item[a].image_name+'"><a target="_blank" href="/admin/files/index?keywords={$keywords}'+item[a].image_name+'"><img class="lazyload" data-href="'+item[a].filepath+'" data-src="'+path+'" src="" alt="'+item[a].filename+'"  class="file-item"><p title="'+item[a].image_name+'">'+item[a].image_name+'</p></a></li>';
							}
						}
						$('#filesBox').html(li);
						$('#laypage').show();
						lazyload();
					}
					else {
						$('#filesBox').html('<div class="empty"><i class="layui-icon layui-icon-upload"></i><p>无文件文件，赶紧去上传吧!</p></div>');
						$('#laypage').hide();
					}
				}
			});
		}

		// 选中/取消选中文件（仅在点击空白区域时）
		$('#filesBox').on('click','li',function(e){
			// 检查点击的是不是图片
			if (!$(e.target).hasClass('file-item')) {
				// 移除所有同类li的on类
				$('#filesBox li').removeClass('on');
				// 给当前点击的li添加on类
				$(this).addClass('on');

				const viewBtn = $(this).find('.file-view-images');
				if (viewBtn.length) {
					viewBtn.trigger('click');
				}
			}
		});

		// 点击图片触发预览
		$('#filesBox').on('click','.file-item',function(e){
			e.stopPropagation(); // 阻止事件冒泡到li元素
			const imgSrc = $(this).data('src') || $(this).attr('src');
			const $li = $(this).closest('li');

			// 触发预览
			const viewBtn = $li.find('.file-view-images');
			if (viewBtn.length) {
				viewBtn.trigger('click');
			}
		})

		$('#filesBox').on('click','.file-edit',function(){
			let id = $(this).parent().parent().data('id');
			let title = $(this).parent().parent().data('title');
			let ext = $(this).parent().parent().data('ext');
			layer.prompt({
				title: '重命名',
				value: title,
				yes: function(index, layero) {
					var value = layero.find(".layui-layer-input").val();
					if (value!='') {
						let callback = function (e) {
							layer.msg(e.msg);
							$('[lay-filter="webform"]').click();
						}
						tool.post("/admin/files/edit", {id: id,title: value+'.'+ext}, callback);
						layer.close(index);
					} else {
						layer.msg('请填写分组名称');
					}
				}
			})
		})

		// 单独删除文件（阻止预览触发）
		$('#filesBox').on('click','.file-del',function(e){
			e.stopPropagation(); // 阻止事件冒泡到预览
			let title = $(this).parent().parent().data('title');
			layer.confirm(`确定要删除文件「${title}」吗？`, { icon: 3, title: '提示' }, function (index) {
				let callback = function (e) {
					layer.closeAll();
					layer.msg(e.msg);
					// 删除成功后刷新页面
					if(e.code==0){
						location.reload();
					}
				}
				const keywords = $('#keywords').val();
				tool.delete("/admin/files/delete", {ids:title,path:keywords}, callback);
			});
		})

		form.on ('submit (webform)', function (data) {
			get_files (data.field);
			return false;
		});
		$('.subject').on ('scroll', function () {
			lazyload.check ();
		});


		// 图片预览放大功能
		function initImagePreview() {
			let imageList = [];
			let currentIndex = 0;

			function updateImageList() {
				imageList = [];
				$('#filesBox li[data-image="true"]').each(function(index, el) {
					imageList.push({
						src: $(el).data('image-src'),
						title: $(el).data('title')
					});
				});
			}

			function showImageByIndex(index) {
				if (imageList.length === 0) return;
				if (index < 0) index = imageList.length - 1;
				if (index >= imageList.length) index = 0;
				currentIndex = index;
				const image = imageList[currentIndex];
				$('#previewImage').attr('src', image.src);
				$('#imageCounter').text(`${currentIndex + 1}/${imageList.length}`);
			}

			// 预览按钮触发预览
			$('#filesBox').on('click', '.file-view-images', function(e) {
				e.stopPropagation();
				const imgSrc = $(this).data('href');
				updateImageList();
				if (imageList.length === 0) return;
				currentIndex = imageList.findIndex(item => item.src === imgSrc);
				if (currentIndex !== -1) {
					showImageByIndex(currentIndex);
					$('#imagePreviewModal').addClass('show');
					$('body').css('overflow', 'hidden');
				}
			});

			$('#prevImage').on('click', function() {
				showImageByIndex(currentIndex - 1);
			});

			$('#nextImage').on('click', function() {
				showImageByIndex(currentIndex + 1);
			});

			function closePreview() {
				$('#imagePreviewModal').removeClass('show');
				$('#previewImage').attr('src', '');
				$('body').css('overflow', 'auto');
			}

			$('#closePreview').on('click', closePreview);
			$('#imagePreviewModal').on('click', function(e) {
				if (e.target === this) {
					closePreview();
				}
			});

			$(document).on('keydown', function(e) {
				if (!$('#imagePreviewModal').hasClass('show')) return;
				switch(e.key) {
					case 'Escape':
						closePreview();
						break;
					case 'ArrowLeft':
						showImageByIndex(currentIndex - 1);
						e.preventDefault();
						break;
					case 'ArrowRight':
						showImageByIndex(currentIndex + 1);
						e.preventDefault();
						break;
				}
			});
		}

		initImagePreview();
	}
</script>
{/block}